package org.ihelpuoo.weboo.security;

import org.ihelpuoo.lang.ArrayUtils;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.weboo.module.ActionContext;

public class RoleRightSessionController extends
		SessionController<RoleRightSessionController.ActionRoles>
{
	@Override
	protected String doCheck(ActionContext context, ActionRoles[] ars) throws Exception
	{
		String actionName = context.getActionnName();
		ActionRoles ar = null;
		for (int i = 0; i < ars.length; i++)
		{
			if (ars[i].match(actionName))
			{
				ar = ars[i];
				break;
			}
		}
		if (null == ar)
			return null;
		Security security = Security.me(context.nut());

		if (!context.getSession().isLogined())
			return security.getFailTarget();

		RoleAccount account = (RoleAccount)context.getSession().getAccount();

		if (ar.canAccess((RoleAccount)account))
			return null;
		return security.getFailTarget();
	}

	@Override
	protected ActionRoles[] parseConifgItem(ActionContext context, String v)
	{
		if (StringUtils.isEmpty(v))
			return new ActionRoles[0];
		Security security = Security.me(context.nut());
		String[] ss = StringUtils.splitIgnoreBlank(v,"[;]");
		ActionRoles[] ars = new ActionRoles[ss.length];
		for (int i = 0; i < ss.length; i++)
		{
			ars[i] = new ActionRoles(ss[i],security);
		}
		return ars;
	}

	class ActionRoles
	{
		String	actionName;
		int[]	roles;

		ActionRoles(CharSequence cs, Security security)
		{
			StringBuffer sb = new StringBuffer();
			int i = 0;
			for (; i < cs.length(); i++)
			{
				char c = cs.charAt(i);
				if (c == ':')
					break;
				sb.append(c);
			}
			actionName = sb.toString();
			String s = cs.subSequence(i + 1,cs.length()).toString();
			String[] ss = StringUtils.splitIgnoreBlank(s);
			if (null == ss || ss.length == 0)
			{
				roles = new int[0];
			}
			else
			{
				roles = new int[ss.length];
				for (i = 0; i < ss.length; i++)
					roles[i] = security.getRole(ss[i]);
			}
		}

		boolean match(String actionName)
		{
			return this.actionName.equals(actionName);
		}

		boolean canAccess(RoleAccount account)
		{
			if (roles.length == 0)
				return false;
			return ArrayUtils.isInArray(roles,account.getRole());
		}
	}
}
